Welcome to Django!

1.8 重定向

重定向(Redirect)用来将用户导航到不同的URL或视图,重定向是在服务器端返回一个特殊的HTTP响应,

该响应包含一个新的URL,告诉客户端浏览器去请求该URL.

重定向内部URL ,如:/hello123 会重定向到/hello

内部定向:

import os.path

from django.conf import settings

from django.contrib import admin

from django.urls import path

from django.shortcuts import HttpResponse,redirect

#视图函数,必需有一个参数

def hello(request):

filepath=os.path.join(settings.BASE_DIR,"shn","hello_world.html")

with open(filepath, "r" ) as f:

content=f.read()

return HttpResponse(content, content_type = "text/html" , status = 200 )

#content_type="text/html" 响应的格式是html格式,也可以改为纯文件格式cotent-type

#status=200 默认响应码是200,也可以修改成其他的3位数字


def hello123(requeet):

return redirect( "/hello" )

# 需要在django.shortcuts里面再导入一个redirect

urlpatterns = [

path( 'admin/' , admin.site.urls),

path( 'hello' , hello),

path( 'hello123' , hello123),

]

# 需要增加地址: path('hello123', hello123),


外定向

def hello123(requeet):

return redirect( "https://www.baidu.com" ) #需要写上一个完整的地址

# 需要在django.shortcuts里面再导入一个redirect,只要输入hello123就能转到问百度